package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.oa.domain.OaAdminAsset;
import com.ruoyi.oa.domain.bo.OaAdminAssetBo;
import com.ruoyi.oa.service.IOaAdminAssetService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaAdminEntryBo;
import com.ruoyi.oa.domain.vo.OaAdminEntryVo;
import com.ruoyi.oa.domain.OaAdminEntry;
import com.ruoyi.oa.mapper.OaAdminEntryMapper;
import com.ruoyi.oa.service.IOaAdminEntryService;
import com.ruoyi.workflow.service.IProcessInstanceService;
import com.ruoyi.workflow.service.IUserService;
import com.ruoyi.workflow.utils.WorkFlowUtils;
import java.util.stream.Collectors;
import java.util.*;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.oa.domain.vo.OaProjectVo;

/**
 * 办公用品入库申请Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-27
 */
@RequiredArgsConstructor
@Service
public class OaAdminEntryServiceImpl implements IOaAdminEntryService {

    private final OaAdminEntryMapper baseMapper;

    private final IProcessInstanceService iProcessInstanceService;

    private final IUserService iUserService;

    private final IOaAdminAssetService iOaAdminAssetService;
    /**
     * 查询办公用品入库申请
     */
    @Override
    public OaAdminEntryVo queryById(String id){
        OaAdminEntryVo vo= baseMapper.selectVoById(id);
        WorkFlowUtils.setStatusFileValue(vo,vo.getId());
        return vo;
    }

    /**
     * 查询办公用品入库申请列表
     */
    @Override
    public TableDataInfo<OaAdminEntryVo> queryPageList(OaAdminEntryBo bo, PageQuery pageQuery) {
        String userName = iUserService.getUserNameByNickName(bo.getCreateBy());
        if (StringUtils.isNotBlank(userName)){
            bo.setCreateBy(userName);
        }
        if (CollectionUtil.isNotEmpty(bo.getSubmitTimeList())){
            bo.setSubmitStartDate(bo.getSubmitTimeList().get(0));
            bo.setSubmitEndDate(bo.getSubmitTimeList().get(1));
        }
        List<OaAdminEntryVo> voList = baseMapper.queryByCondition(bo);
        // 添加流程信息
        if (CollectionUtil.isNotEmpty(voList)) {
            List<String> list = voList.stream().map(OaAdminEntryVo::getId).collect(Collectors.toList());
            WorkFlowUtils.setStatusListFileValue(voList, list, "id");
        }
        // 筛选状态
        if (StringUtils.isNotBlank(bo.getStatus())) {
            List<OaAdminEntryVo> temp = new ArrayList<>();
            for (OaAdminEntryVo vo : voList) {
                if (vo.getActBusinessStatus().getStatus().equals(bo.getStatus())) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }
        // 筛选提交时间
        if (CollectionUtil.isNotEmpty(bo.getSubmitTimeList())) {
            List<OaAdminEntryVo> temp = new ArrayList<>();
            Date submitStartDate = bo.getSubmitStartDate();
            Date submitEndDate = bo.getSubmitEndDate();
            for (OaAdminEntryVo vo : voList) {
                Date createTime = vo.getActBusinessStatus().getCreateTime();
                if (ObjectUtil.isNotEmpty(createTime) && createTime.after(submitStartDate) && createTime.before(submitEndDate)) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }

        // 筛选提交人
        if (StringUtils.isNotEmpty(bo.getCreateBy())) {
            List<OaAdminEntryVo> temp = new ArrayList<>();
            for (OaAdminEntryVo vo : voList) {
                if (ObjectUtil.isNotEmpty(vo.getActBusinessStatus().getCreateTime()) && vo.getActBusinessStatus().getCreateBy().equals(bo.getCreateBy())) {
                    temp.add(vo);
                }
            }
            voList = temp;
        }
        Page<OaAdminEntryVo> result = new Page<>();
        result.setTotal(voList.size());

        int start = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        int end = Math.min(pageQuery.getPageNum() * pageQuery.getPageSize(), voList.size());
        voList = voList.subList(start, end);

        result.setRecords(voList);
        result.setCurrent(pageQuery.getPageNum());
        result.setSize(pageQuery.getPageSize());

        return TableDataInfo.build(result);
    }

    /**
     * 查询办公用品入库申请列表
     */
    @Override
    public List<OaAdminEntryVo> queryList(OaAdminEntryBo bo) {
        LambdaQueryWrapper<OaAdminEntry> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OaAdminEntry> buildQueryWrapper(OaAdminEntryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OaAdminEntry> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getEntryDate() != null, OaAdminEntry::getEntryDate, bo.getEntryDate());
        lqw.like(StringUtils.isNotBlank(bo.getProductName()), OaAdminEntry::getProductName, bo.getProductName());
        return lqw;
    }

    /**
     * 新增办公用品入库申请
     */
    @Override
    public OaAdminEntryBo insertByBo(OaAdminEntryBo bo) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        bo.setDeptId(currentUser.getDeptId());
        bo.setUserId(currentUser.getUserId());
        OaAdminEntry add = BeanUtil.toBean(bo, OaAdminEntry.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return bo;
    }

    /**
     * 修改办公用品入库申请
     */
    @Override
    public OaAdminEntry updateByBo(OaAdminEntryBo bo) {
        OaAdminEntry update = BeanUtil.toBean(bo, OaAdminEntry.class);
        validEntityBeforeSave(update);
        int i =baseMapper.updateById(update);
        return update;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OaAdminEntry entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除办公用品入库申请
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        for (String id : ids) {
            String processInstanceId = iProcessInstanceService.getProcessInstanceId(id);
            if (StringUtils.isNotBlank(processInstanceId)) {
                iProcessInstanceService.deleteRuntimeProcessAndHisInst(processInstanceId);
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    public void InputToAsset(String id){
        OaAdminEntryVo oaAdminEntryVo = baseMapper.selectVoById(id);
        if (oaAdminEntryVo.getIsAsset().equals("1")){
            //已存在
            OaAdminAsset oaAdminAsset = iOaAdminAssetService.checkHasOneData(oaAdminEntryVo.getAssetType(), oaAdminEntryVo.getAssetCode(), oaAdminEntryVo.getProductName());
            oaAdminAsset.setInputNum(oaAdminAsset.getInputNum()+Integer.parseInt(oaAdminEntryVo.getWareNum()));
            oaAdminAsset.setLeaveCount(oaAdminAsset.getLeaveCount()+Integer.parseInt(oaAdminEntryVo.getWareNum()));
            OaAdminAssetBo update = BeanUtil.toBean(oaAdminAsset, OaAdminAssetBo.class);
            Boolean aBoolean = iOaAdminAssetService.updateByBo(update);
        }else {
            OaAdminAsset oaAdminAsset = new OaAdminAsset();
            //不存在
            oaAdminAsset.setAssetType(oaAdminEntryVo.getAssetType());
            oaAdminAsset.setAssetCode(oaAdminEntryVo.getAssetCode());
            oaAdminAsset.setProductName(oaAdminEntryVo.getProductName());
            oaAdminAsset.setInputNum(Integer.parseInt(oaAdminEntryVo.getWareNum()));
            oaAdminAsset.setLeaveCount(Integer.parseInt(oaAdminEntryVo.getWareNum()));
            OaAdminAssetBo update = BeanUtil.toBean(oaAdminAsset, OaAdminAssetBo.class);
            Boolean aBoolean = iOaAdminAssetService.insertByBo(update);
        }
    }

    public JSONObject getAllHasFinishEntry(){
        JSONObject jsonObject = new JSONObject();
        List<OaAdminEntryVo> oaAdminEntryVos = baseMapper.selectVoList(new LambdaQueryWrapper<>());
        if (CollectionUtil.isNotEmpty(oaAdminEntryVos)) {
            List<String> list = oaAdminEntryVos.stream().map(OaAdminEntryVo::getId).collect(Collectors.toList());
            WorkFlowUtils.setStatusListFileValue(oaAdminEntryVos, list, "id");
        }

        if (CollectionUtil.isNotEmpty(oaAdminEntryVos)) {
            oaAdminEntryVos = oaAdminEntryVos.stream().filter(d -> d.getActBusinessStatus().getStatus().equals("finish")).collect(Collectors.toList());
        }
        if (CollectionUtil.isNotEmpty(oaAdminEntryVos)) {
            int sum = 0;
            List<String> collect = oaAdminEntryVos.stream().map(d -> d.getWareNum()).collect(Collectors.toList());
            for (String numStr : collect) {
                int num = Integer.parseInt(numStr);
                sum += num;
            }
            jsonObject.put("total",oaAdminEntryVos.size());
            jsonObject.put("sum",sum);
        }else {
            jsonObject.put("total",0);
            jsonObject.put("sum",0);
        }
        return jsonObject;

    }
}
